﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Web.Http;
using Windows.Web.Http.Headers;
using douban.Core.Utils;
using Newtonsoft.Json;

namespace douban.Core.Apis
{
    public partial class Api
    {
        public static async Task<string> Get(string url, IEnumerable<KeyValuePair<string, string>>  queryData = null,bool bearer = true)
        {
            if (queryData == null)
            {
                queryData = new List<KeyValuePair<string, string>>();
            }
            queryData = queryData.Union(new[] {new KeyValuePair<string, string>("apikey",Common.API_KEY), });
            Action<HttpClient> buildHeaders = null;
            if (bearer)
            {
                buildHeaders = BuildHeaders;
            }
            return await WebUtil.Get(url, queryData, buildHeaders);
        }

        public static async Task<string> PostWithBearer(string url, IEnumerable<KeyValuePair<string, string>>  data
            , IEnumerable<KeyValuePair<string, string>> queryData = null
            , bool bearer = true)
        {
            if (queryData == null)
            {
                queryData = new List<KeyValuePair<string, string>>();
            }
            queryData = queryData.Union(new[] { new KeyValuePair<string, string>("apikey", Common.API_KEY), });
            Action<HttpClient> buildHeaders = null;
            if (bearer)
            {
                buildHeaders = BuildHeaders;
            }
            return await WebUtil.Post(url, data, queryData, buildHeaders);
        }


        public static async Task<string> Search(string url
            , IEnumerable<KeyValuePair<string, string>> queryData = null
            , int start = 0, int count = 20,bool bearer = true)
        {
            if (queryData == null)
            {
                queryData = new List<KeyValuePair<string,string>>();
            }
            queryData = queryData.Union(new[]
            {
                new KeyValuePair<string, string>("count",count.ToString()),
                new KeyValuePair<string, string>("start",start.ToString()),
            });
            return await Get(url, queryData,bearer);
        }

        public static string BuildUri(string url,params object[] args)
        {
            url = string.Format("https://{0}{1}", Common.HOST, url);
            return string.Format(url, args);
        }


        private static void BuildHeaders(HttpClient httpClient)
        {
            httpClient.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("Bearer", Common.Token);
        }
    }
}
